package cn.anzhiyublog.staranimegallery.util;

import cn.anzhiyublog.staranimegallery.exception.GalleryException;
import cn.anzhiyublog.staranimegallery.model.dto.picture.PictureSpiderUploadRequest;
import cn.anzhiyublog.staranimegallery.model.enums.StatusCode;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 解析html工具
 *
 * @author 安知一只鱼
 */
@Component
@Slf4j
public class JsoupUtils {
    /**
     * 搜索引擎选择
     *
     * @param searchEngine 搜索引擎名称，支持 "bing"、"baidu"、"sogou"
     * @return 对应的搜索引擎图片搜索 URL
     */
    public String selectEngine(String searchEngine) {
        String bingUrl = "https://cn.bing.com/images/async?q=%s&first=%d&count=%d&mmasync=1";
        if (searchEngine == null) {
            // 如果传入的搜索引擎名称为 null，使用默认的必应搜索引擎
            return bingUrl;
        }
        switch (searchEngine.toLowerCase()) {
            case "bing":
                return bingUrl;
            /* 百度图片和搜狗图片都有防爬qwq，下次有空再研究研究 */
            case "baidu":
                throw new GalleryException(StatusCode.INTERNAL_SERVER_ERROR, "暂未实现百度图片搜索");
            case "sogou":
                throw new GalleryException(StatusCode.INTERNAL_SERVER_ERROR, "暂未实现搜狗图片搜索");
            default:
                throw new GalleryException(StatusCode.NOT_ACCEPTABLE, "没有此搜索方法");
        }
    }

    /**
     * 搜索 url 构造
     *
     * @param searchEngine 搜索引擎名称，支持 "bing"、"baidu"、"sogou"
     * @param query        搜索条件
     * @param first        分页
     * @param count        单页个数
     * @return 构造好的完整搜索 URL
     */
    public String constructSearchUrl(String searchEngine, String query, int first, int count) {
        // 一些校验
        ThrowUtils.throwIf(query.length()>20, StatusCode.BAD_REQUEST, "搜索条件不能超过20个字符");
        ThrowUtils.throwIf(first<0, StatusCode.BAD_REQUEST, "分页参数不能小于0");
        ThrowUtils.throwIf(count<1, StatusCode.BAD_REQUEST, "单页个数不能小于1");
        ThrowUtils.throwIf(count>25, StatusCode.BAD_REQUEST, "单页个数不能超过25");
        String baseUrl = selectEngine(searchEngine);
        return String.format(baseUrl, query, first, count);
    }
    public String constructSearchUrl(PictureSpiderUploadRequest pictureSpiderUploadRequest) {
        String searchEngine = ObjectUtil.defaultIfNull(pictureSpiderUploadRequest.getSearchEngine(), "bing");
        String query = pictureSpiderUploadRequest.getKeyword();
        int first = ObjectUtil.defaultIfNull(pictureSpiderUploadRequest.getCurrent(), 1);
        int count = ObjectUtil.defaultIfNull(pictureSpiderUploadRequest.getSize(), 10);
        return constructSearchUrl(searchEngine, query, first, count);
    }
    // 默认查询
    public String constructSearchUrl(String query) {
        return constructSearchUrl("bing", query, 1, 10);
    }

    /**
     * 获取页面
     */
    public Document getPage(PictureSpiderUploadRequest pictureSpiderUploadRequest){
        Document document;
        try {
            String url = constructSearchUrl(pictureSpiderUploadRequest);
            document = Jsoup.connect(url).get();
            return document;
        }catch (IOException e){
            log.error("--LOGGING-- 获取页面失败：{}", String.valueOf(e));
            throw new GalleryException(StatusCode.INTERNAL_SERVER_ERROR, "获取页面失败");
        }
    }

    /**
     * 获取图片元素列表
     */
    public Elements getImages(Document document){
        Element dgControl = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(ObjectUtil.isNull(dgControl), StatusCode.INTERNAL_SERVER_ERROR, "获取图片元素列表失败");
        return dgControl.select("img.mimg");
    }
}
